//
//  LPTRegisterViewController.m
//  LPTClient
//
//  Created by apple on 2018/12/4.
//  Copyright © 2018 zhaodd. All rights reserved.
//

#import "LPTRegisterViewController.h"
#import "NSString+Category.h"
#import "MMProgressHUD.h"
#import "LPTBaseRequest.h"
#import "LPTWebViewController.h"
#import "AppDelegate.h"

@interface LPTRegisterViewController ()
{
    BOOL isDelay;
}

@property (nonatomic, weak) IBOutlet UIScrollView *mainScrollview;

@property (nonatomic, weak) IBOutlet UITextField *phoneTextField;
@property (nonatomic, weak) IBOutlet UITextField *passTextField;
@property (nonatomic, weak) IBOutlet UITextField *codeTextField;
@property (nonatomic, weak) IBOutlet UITextField *inviteTextField;
@property (nonatomic, weak) IBOutlet UIButton *codeButton;
@property (nonatomic, weak) IBOutlet UIButton *protocolBtn;
@property (nonatomic, weak) NSTimer *m_timer;
@property (nonatomic, assign) NSInteger count;

@end

@implementation LPTRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [_mainScrollview setContentSize:CGSizeMake(kScreenWidth, _mainScrollview.height + 10000)];
    isDelay = NO;
    [self setupLabelProtocol];
}

- (IBAction)backToLogin:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupLabelProtocol
{
    NSString *preStr = @"注册即代表您已经同意";
    NSString *rightStr = @"喜郞中APP用户协议";
    
    NSString *str = [NSString stringWithFormat:@"%@%@", preStr,rightStr];
    
    NSMutableAttributedString *mutableAttributedStr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{ NSForegroundColorAttributeName: [UIColor grayColor] }];
    [mutableAttributedStr addAttribute:NSLinkAttributeName value:@"toProtocolAction" range:NSMakeRange(preStr.length, rightStr.length)];
    [mutableAttributedStr setAttributes:@{ NSForegroundColorAttributeName: [UIColor orangeColor] } range:NSMakeRange(preStr.length, rightStr.length)];

    [self.protocolBtn setAttributedTitle:mutableAttributedStr forState:UIControlStateNormal];
}

- (IBAction)goToAction:(id)ge
{
    // 去网页
    LPTWebViewController *vc = [LPTWebViewController instanceWithUrl:@"https://doctor.5ixlz.com/common/article_detail?slug=doctor-protocol"];
    [self.navigationController pushViewController:vc animated:YES];
}



// 回到登录 界面
- (IBAction)goToLogin:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 验证码点击
- (IBAction)codeClickAction:(id)sender
{
    [self getVerifyCode];
}

// 提交
- (IBAction)commitRegisterAction:(id)sender
{
    [MMProgressHUD showWithStatus:@"提交中"];
    
    NSString *telephone = self.phoneTextField.text;
    NSString *password = self.passTextField.text;
    NSString *code = self.codeTextField.text;
    NSString *invitePhone = self.inviteTextField.text;

    if (!telephone.isMobileNumber)
    {
        [MMProgressHUD dismissWithError:@"手机号格式有误"];
        return;
    }
    if (invitePhone.length > 0 && !invitePhone.isMobileNumber)
    {
        [MMProgressHUD dismissWithError:@"邀请人手机号格式有误"];
        return;
    }
    if (password.length == 0)
    {
        [MMProgressHUD dismissWithError:@"请输入密码"];
        return;
    }
    if (code.length == 0)
    {
        [MMProgressHUD dismissWithError:@"请输入验证码"];
        return;
    }
    
    NSDictionary *body = @{@"mobile": telephone,
                           @"invite_mobile": invitePhone,
                           @"password" : password,
                           @"code": code
                           };
    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:@"/api/register" withBody:body withMethod:YTKRequestMethodPOST];
    request.needLogin = NO;
    
    [request startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {

        [MMProgressHUD dismiss];
        [[LTPCacheManager shareInstance] setToken:data[@"token"]];
        [self dismissViewControllerAnimated:NO completion:NULL];
        
        [((AppDelegate*)[UIApplication sharedApplication].delegate) loadMainVC];
        
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"refresh_login_userinfo" object:nil];
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        [MMProgressHUD dismissWithError:request.msg];
        
    }];

}

- (void)getVerifyCode
{
    [MMProgressHUD showWithStatus:@"获取验证码中"];

    NSString *telephone = self.phoneTextField.text;
    
    if (!telephone.isMobileNumber)
    {
        [MMProgressHUD dismissWithError:@"请输入正确的手机号"];
        return;
    }

    NSDictionary *body = @{};
    NSString *apiName = [NSString stringWithFormat:@"/common/send_sms_code/%@", telephone];
    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:apiName withBody:body withMethod:YTKRequestMethodGET];
    
    [request startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        // 8336  是成功 
        [MMProgressHUD dismissWithSuccess:@"验证码发送成功"];
        [self codeStart];
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        [MMProgressHUD dismissWithError:request.msg];
        
    }];
}

- (void)codeStart
{
    if (isDelay) {
        return;
    }
    _count = 60;
    [self.codeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.codeButton setTitle:@"60s" forState:UIControlStateNormal];
    self.m_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChange:) userInfo:nil repeats:YES];
    
    isDelay = YES;
}

- (void)timeChange:(NSTimer *)timer
{
    if (_count > 1)
    {
        _count--;
        NSString *str = [NSString stringWithFormat:@"%lds",(long)_count];
        [self.codeButton setTitle:str forState:UIControlStateNormal];
    }
    else
    {
        isDelay = NO;

        [timer invalidate];
        self.m_timer = nil;
        [self.codeButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [self.codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
}

@end
